package code._15network.tcp.v2;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Service {
    public static void main(String[] args) throws IOException{
        //创建服务端socket
        ServerSocket serverSocket = new ServerSocket(9999);
        //创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        //多客户端连接  accept while
        while (true){
            //建立连接
            Socket socket = serverSocket.accept();
            //提交任务到线程池
            Future<?> submit = threadPool.submit(new ConnectTask(socket));
        }
        //使用线程池

    }
}

//任务
class ConnectTask implements Runnable{
    Socket socket;

    public ConnectTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream in=null;
        try {
            in=socket.getInputStream();
            while(true){
                //从socket读取消息
                byte[] bytes = new byte[1024];
                int readCount = in.read(bytes);
                String msg=new String(bytes,0,readCount);
                System.out.println("msg = " + msg);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
